<template>
  <div class="viewBox">
    <div class="view_title">
      <div class="text-16px">任务数据</div>
      <div class="flex items-center cursor-pointer">
        <el-radio-group v-model="queryParams.datetype" @change="dataTypeChange">
          <el-radio-button label="w">本周</el-radio-button>
          <el-radio-button label="m">本月</el-radio-button>
          <el-radio-button label="y">本年</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="viewsCnt p-20px">
      <div class="echarts w-100% h-250px relative pt-30px">
        <div class="font-bold absolute left-10px top-10px text-14px text-#666">
          任务类型
        </div>
        <div
          class="font-bold absolute left-50% pl-20px top-10px text-14px text-#666"
        >
          任务处理情况
        </div>
        <div id="echarts-main-left" class="w-50% h-100% inline-block"></div>
        <div id="echarts-main-right" class="w-50% h-100% inline-block"></div>
      </div>
      <div class="progress mt-40px">
        <div
          class="box w-32% inline-block mr-1%"
          v-for="(el, index) in progressList"
          :key="index"
        >
          <div class="text-14px text-#666 font-bold">{{ el.name }}</div>
          <div
            class="bg-#f2f6fc pt-10px pl-10px mt-15px pr-10px pb-20px rounded-5px"
          >
            <div class="progress" v-for="(item, i) in el.row" :key="i">
              <div class="line">
                <div
                  class="bar"
                  :style="{
                    backgroundColor: progressColor[i],
                    width: item.mix
                  }"
                ></div>
                <div
                  v-if="item.value != '0'"
                  class="text"
                  :title="item.mix"
                  :style="{
                    width: item.mix
                  }"
                >
                  {{ item.mix }}
                </div>
              </div>
              <div class="name">{{ item.name }} {{ item.value }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="TaskData">
import * as echarts from 'echarts'
import { getformdata } from '@/api/businessSettings/task'
import { useRouter } from 'vue-router'
import 'echarts/theme/macarons.js'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const loading = ref(false)
const data = reactive({
  queryParams: {
    datetype: 'w'
  },
  progressColor: ['#09f', '#51d351', '#ffa94c'],
  progressDat: [
    { value: 0, name: '待处理', mix: '0.0%' },
    { value: 0, name: '已完结', mix: '0.0%' },
    { value: 0, name: '已退回', mix: '0.0%' }
  ],
  progressList: []
})

const { queryParams, progressColor, progressList, progressDat } = toRefs(data)

async function init() {
  loading.value = true
  await getList()
}
// 请求接口
function getList() {
  getformdata({
    ...queryParams.value,
    id: userStore.user.userId
  })
    .then(async res => {
      if (res.code == 200) {
        loading.value = false
        await dealDta(res.data)
      }
    })
    .catch(() => {
      loading.value = false
    })
}
// 时间改变
const dataTypeChange = val => {
  getList()
}
/**
 * return
 * taskType 任务类型
 * testProblem 测试问题
 * productionBug 生成bug
 * functionNeed 功能需求
 * dealState 任务出来情况
 * pending 待处理
 * processed 已处理
 * returned 已退回
 * developmentTask研发任务
 * doorToDoorService 上门服务
 * followUpTask 跟进任务
 */
const dealDta = obj => {
  let data = JSON.parse(JSON.stringify(obj))
  let taskType = [
    { value: 0, name: '跟进任务' },
    { value: 0, name: '研发任务' },
    { value: 0, name: '上门服务' }
  ]
  let dealState = [
    { value: 0, name: '已处理' },
    { value: 0, name: '待处理' },
    { value: 0, name: '已退回' }
  ]
  let testProblem = progressDat.value
  let productionBug = progressDat.value
  let functionNeed = progressDat.value
  // 任务类型
  if (data.taskType) {
    taskType = Object.entries(data.taskType).map(([key, value]) => ({
      value: parseInt(value),
      name:
        key === 'followUpTask'
          ? '跟进任务'
          : key === 'doorToDoorService'
          ? '上门服务'
          : '研发任务'
    }))
  }
  //任务处理情况
  if (data.dealState) {
    dealState = Object.entries(data.dealState).map(([key, value]) => ({
      value: parseInt(value),
      name:
        key === 'processed' ? '已处理' : key === 'pending' ? '待处理' : '已退回'
    }))
  }
  let testSum =
    parseInt(data.testProblem.pending) +
    parseInt(data.testProblem.processed) +
    parseInt(data.testProblem.returned)
  // 测试问题
  testProblem = data.testProblem
    ? Object.entries(data.testProblem).map(([key, value]) => {
        return {
          value: parseInt(value),
          mix:
            testSum < 1 ? '0.0%' : ((value / testSum) * 100).toFixed(1) + '%',
          name:
            key === 'pending'
              ? '待处理'
              : key === 'processed'
              ? '已完结'
              : '已退回'
        }
      })
    : progressDat.value
  // 生产BUG
  let bugSum =
    parseInt(data.productionBug.pending) +
    parseInt(data.productionBug.processed) +
    parseInt(data.productionBug.returned)
  productionBug = data.productionBug
    ? Object.entries(data.productionBug).map(([key, value]) => ({
        value: parseInt(value),
        mix: bugSum < 1 ? '0.0%' : ((value / bugSum) * 100).toFixed(1) + '%',
        name:
          key === 'pending'
            ? '待处理'
            : key === 'processed'
            ? '已完结'
            : '已退回'
      }))
    : progressDat.value
  // 功能需求
  let needSum =
    parseInt(data.functionNeed.pending) +
    parseInt(data.functionNeed.processed) +
    parseInt(data.functionNeed.returned)
  functionNeed = data.functionNeed
    ? Object.entries(data.functionNeed).map(([key, value]) => ({
        value: parseInt(value),
        mix: needSum < 1 ? '0.0%' : ((value / needSum) * 100).toFixed(1) + '%',
        name:
          key === 'pending'
            ? '待处理'
            : key === 'processed'
            ? '已完结'
            : '已退回'
      }))
    : progressDat.value
  proxy.$nextTick(() => {
    disposeEcharts()
    echartsInit({
      id: 'echarts-main-left',
      color: ['#FF7A8C', '#8167F5', '#52C1F5'],
      name: '任务类型',
      data: taskType
    })
    echartsInit({
      id: 'echarts-main-right',
      color: ['#82d588', '#fec03d', '#52c1f5'],
      name: '任务处理情况',
      data: dealState
    })
    progressList.value = [
      { name: '测试问题', row: testProblem },
      { name: '生产BUG', row: productionBug },
      { name: '功能需求', row: functionNeed }
    ]
  })
}

/**
 * echarts 配置
 * @param {*} dat 数据配置
 */
function echartsInit(dat) {
  let totalVal = 0
  if (dat && dat.data) {
    dat.data.map(item => {
      totalVal += item.value
    })
  }
  let chartDom = document.getElementById(dat.id)
  let myChart = echarts.init(chartDom, 'macarons')
  let option = {
    title: {
      text: totalVal,
      subtext: '全部任务',
      left: 'center',
      top: 'middle',
      subtextStyle: {
        fontSize: '14',
        color: '#999'
      },
      itemGap: 0, //主副标题的距离
      textStyle: {
        fontSize: '28',
        color: '#666',
        fontWeight: 'bold'
      }
    },
    color: dat.color,
    tooltip: {
      trigger: 'item'
    },
    // grid: {
    //   left: '30px',
    //   right: '300px',
    //   bottom: '100px'
    // },
    // legend: {
    //   orient: '',
    //   x: 'right', //可设定图例在左、右、居中
    //   y: 'center', //可设定图例在上、下、居中
    //   textStyle: {
    //     fontSize: '14',
    //     color: '#999'
    //   },
    //   itemGap: 20,
    //   itemWidth: 10,
    //   itemHeight: 10,
    //   icon: 'circle'
    // },
    // 回调函数
    // formatter: function (obj) {
    //   let text
    //   if (typeof obj == 'string') {
    //     text = obj
    //   } else {
    //     text = obj.name
    //   }
    //   let data = option.series[0].data //获取series中的data
    //   let tarValue
    //   if (data) {
    //     for (let i = 0, l = data.length; i < l; i++) {
    //       if (data[i].name == text) {
    //         tarValue = data[i].value
    //       }
    //     }
    //   }
    //   var p = totalVal < 1 ? 0 : ((tarValue / totalVal) * 100).toFixed(1)
    //   return text + ' ' + ' ' + p + '%'
    // },
    series: [
      {
        name: dat.name,
        type: 'pie',
        radius: ['55%', '75%'],
        avoidLabelOverlap: false,
        label: {
          //饼图图形上的文本标签
          normal: {
            textStyle: {
              color: '#666',
              fontSize: '13px' //文字的字体大小
            },

            formatter: function (data) {
              let a = data.name //名称
              let c = data.value //值
              var p = totalVal < 1 ? 0 : ((c / totalVal) * 100).toFixed(1)
              return a + p + '%'
            }
          }
        },
        labelLine: {
          normal: {
            length: 15, //第一条线
            length2: 5, //第二条线
            lineStyle: {
              width: 1, // 线条的宽度
              color: '#666' //线的颜色设置， 如没有设置颜色则线条的颜色跟随饼状图的颜色
            }
          }
        },
        data: dat.data
      }
    ]
  }

  option && myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}
init()
const disposeEcharts = () => {
  // 销毁echarts实例
  let chartDom = document.getElementById('echarts-main-left')
  echarts.dispose(chartDom)

  chartDom = document.getElementById('echarts-main-right')
  echarts.dispose(chartDom)
}
onBeforeUnmount(() => {
  disposeEcharts()
})
</script>

<style scoped lang="scss">
.viewBox {
  // height: 420px;
  margin-bottom: 20px;
  :deep(.el-table) {
    margin: 0 !important;
  }
  .read_icon {
    width: 24px;
    height: 23px;
    float: left;
    img {
      vertical-align: center;
      width: 24px;
      height: 18px;
    }
  }
  .urg_icon {
    float: left;
    margin: 0 6px;
    height: 23px;
    img {
      vertical-align: center;
      width: 18px;
      height: 16px;
      margin-top: 2px;
    }
  }
  .view_title {
    background-color: rgba(249, 249, 249, 1);
    padding: 0 20px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    border: 1px solid rgba(223, 220, 220, 0.8);
    border-bottom: none;
    font-family: '微软雅黑 Bold';
    font-weight: 600;
    // box-shadow: 0px 1px 3px 1px rgb(201, 197, 197);
  }
}
.viewsCnt {
  border: 1px solid rgba(223, 220, 220, 0.8);
  margin-bottom: 20px;
  .title {
    font-weight: 700;
  }
  .progress {
    @apply mt-20px;
    .line {
      width: calc(100% - 80px);
      @apply bg-#ebeef5 inline-block h-16px relative;
      .bar {
        @apply absolute top-0px left-0px h-100%;
      }
      .text {
        @apply absolute top-0px left-0px h-100% z-2 text-#fff text-center;
      }
    }
    .name {
      line-height: 21px;
      vertical-align: bottom;
      @apply tetx-14px text-#666 inline-block pl-10px w-80px;
    }
  }
}
</style>
